const fetch = require('../../request/fetch')
Page({
  data: {
    time:null ,
    clockMsg:'',
    title: '', // 单前题目
    optionList: [], // 当前题数
    type: '', //题目类型
    currentTopicNum: "", // 当前题数
    id: '', // 当前题目的id
    choice: '', // 选中的答案
    checkbox: '', // 多选选择的答案
    currentScore: '', //当前分数
    res: '', // 正确的答案
    right: '', // 学生选择的答案
    deadline: '', // 截取时间
    myindex: null, // 选中的索引值
    clock: '',
    next: 0, //下一页
    submitLoading: false,
    page: 0, // 下一页数
    selection: '',
    timer: null
  },
  onLoad: function (options) {

  },
  clock(milliseconds) {
    if(milliseconds < 0){//倒计时完成
      clearInterval(this.wxTimer);
      this.triggerEvent("fetchData");
      return;
    }
    let clockMsg;
    let secondTime = parseInt(milliseconds);// 秒
    let minuteTime = 0;// 分
    let hourTime = 0;// 小时
    if (secondTime > 60) {//如果秒数大于60，将秒数转换成整数
      //获取分钟，除以60取整数，得到整数分钟
      minuteTime = parseInt(secondTime / 60);
      //获取秒数，秒数取佘，得到整数秒数
      secondTime = parseInt(secondTime % 60);
      //如果分钟大于60，将分钟转换成小时
      if (minuteTime > 60) {
        //获取小时，获取分钟除以60，得到整数小时
        hourTime = parseInt(minuteTime / 60);
        //获取小时后取佘的分，获取分钟除以60取佘的分
        minuteTime = parseInt(minuteTime % 60);
      }
    }
    minuteTime = this.formatTime(minuteTime);
    secondTime = this.formatTime(secondTime);
    if(hourTime > 0){
        hourTime = this.formatTime(hourTime);
        clockMsg = `${hourTime}:${minuteTime}:${secondTime}`;
    } else{
        clockMsg = `${minuteTime}:${secondTime}`;
    }
    // console.log("clockMsg：",clockMsg)
    this.setData({
      clockMsg
    })
  },
  //格式化时间
formatTime(data){
  return data < 10 ? `0${data}` : data;
},
  onShow() {
    this.getInit()
  },
  //获取题目信息
  getTopicFn() {
    const that = this
    return new Promise((resolve, reject) =>{
      fetch.getTopic({
        data: {
          // num: this.data.page + 1
        }
      }).then(res => {
        // console.log(res.resCode == 401);
        if(res.resCode == 401){
          wx.reLaunch({
            url: '/pages/rule/rule',
          })
        }
        if (res.message == '已答题100道') {
          wx.reLaunch({
            url: `/pages/end/end`,
          })
        } else {

          this.setData({
            // page: this.data.page + 1,
            next: 0,
            myindex: null,
            choice:''
          })


          for (let i = 0; i < res.data.optionList.length; i++) {
            res.data.optionList[i].isBoole = false
            res.data.optionList[i].ids = false
          }
          let {
            currentTopicNum,
            id,
            optionList,
            type,
            title
          } = res.data
          that.setData({
            currentTopicNum,
            id,
            optionList,
            title,
            type
          })
        }
        resolve(res)
      })
    })
    
  },
  getInit(){
    Promise.all([this.getTopicFn(),this.getUserInfoNum()]).then(res => {
      this.clock(this.data.time);//立即执行
      if(this.wxTimer){
        setInterval(this.wxTimer, 1000);
      }else{
        this.setDateTime()
      }
    })
  },
  setDateTime(){
    this.wxTimer = setInterval(()=>{//隔一秒执行
      if(this.data.time == 0){
        clearInterval(this.wxTimer);
          wx.reLaunch({
            url: '/pages/end/end',
          })
      }else{
        this.setData({
          time :this.data.time -= 1
        })
        this.clock(this.data.time);
      }
    },1000);
  },
  getUserInfoNum() {
    const that = this
    const user = wx.getStorageSync('user')
    return new Promise((resolve, reject) =>{
      fetch.getUserInfo({
        data: user.userId
      }).then(res => {
        // console.log(res.data.startTime,1111111111111111);
        if (!['','Num', null,'null'].includes(res.data.startTime)) {
          this.setData({
            time:Number(res.data.startTime),
            currentScore:res.data.score
          })
        }else{
          this.setData({
            time:6000
          })
        }
        resolve(res)
      })
    })

  },
  // 单选题选中的
  checked(e) {
    let index = e.currentTarget.dataset.index
    let item = this.data.optionList[index]
    item.isBoole = !item.isBoole
    this.setData({
      optionList: this.data.optionList
    })
    let choice = this.data.optionList[index].choice.charAt(0)
    // console.log("选择的答案",choice);
    let newArr = []
    for (let k = 0; k < this.data.optionList.length; k++) {
      if (this.data.optionList[k].isBoole == true) {
        newArr.push(this.data.optionList[k].choice.charAt(0))
      }
    }
    this.setData({
      myindex: index,
      choice: choice, // 单选
      checkbox: newArr.toString()
    })
  },
  // 单选确认按钮
  confirmBtn() {
    if (this.data.choice == '') {
      wx.showToast({
        title: '请选择你的答案',
        icon: 'none',
        duration: 2000,
      })
    } else {
      fetch.answer({
        data: {
          answer: this.data.choice,
          num: this.data.currentTopicNum,
          topicId: this.data.id
        }
      }).then(res => {
        // console.log(res);
        let {
          currentScore,
          right
        } = res.data
        let myres = res.data.res
        myres = right
        if (myres == "D") {
          this.setData({
            selection: 3
          })
        } else if (myres == "A") {
          this.setData({
            selection: 0
          })
        } else if (myres == "B") {
          this.setData({
            selection: 1
          })
        } else if (myres == "C") {
          this.setData({
            selection: 2
          })
        }
        // console.log("正确的答案",myres);
        this.setData({
          currentScore,
          res: myres,
          right,
          next: 1,
        })
      })
    }

  },
  // 多选确认按钮
  checkBtn() {
    if (this.data.choice == '') {
      wx.showToast({
        title: '请选择你的答案',
        icon: 'none',
        duration: 2000,
      })
    } else {
      fetch.answer({
        data: {
          answer: this.data.checkbox,
          num: this.data.currentTopicNum,
          topicId: this.data.id
        }
      }).then(res => {
  
        let {
          currentScore,
          right
        } = res.data
        let myres = res.data.res
        let chars = right.split(",")
        for (let i = 0; i < this.data.optionList.length; i++) {
          if (right.indexOf('A') !== -1) {
            this.data.optionList[0].ids = true
            this.setData({
              optionList: this.data.optionList
            })
          }
          if (chars.indexOf('B') !== -1) {
            this.data.optionList[1].ids = true
            this.setData({
              optionList: this.data.optionList
            })
          }
          if (chars.indexOf('C') !== -1) {
            this.data.optionList[2].ids = true
            this.setData({
              optionList: this.data.optionList
            })
          }
          if (chars.indexOf('D') !== -1) {
            this.data.optionList[3].ids = true
            this.setData({
              optionList: this.data.optionList
            })
          }
        }

        this.setData({
          currentScore,
          res: myres,
          right,
          next: 1,
        })
      })
    }
  },
  // 下一题按钮
  nextTo() {
  const getTopicFn = this.getTopicFn
  this.debounce(getTopicFn)
    
  },
   /*函数防抖*/
  debounce(fn, interval) {
    const that = this
    var gapTime = interval || 1000;//间隔时间，如果interval不传，则默认1000ms
      if(this.data.timer !== null){
        clearTimeout(this.data.timer);
      }
      var context = this;
      var args = arguments;//保存此处的arguments，因为setTimeout是全局的，arguments不是防抖函数需要的。
      this.data.timer = setTimeout(function () {
        fn.call(context, args);
        fn()
        clearTimeout(that.data.timer);
      }, gapTime);
  },
  onHide() {
    fetch.secedeFn({
      data: {
        startTime: this.data.time
      }
    })
    if(this.wxTimer){
      clearInterval(this.wxTimer);
    }
    
  },

  // 提交按钮
  toSubmit() {
    const that = this
    wx.showModal({
      title: '提示',
      content: '是否提前交卷?',
      success(res) {
        if (res.confirm) {
          fetch.overFn({}).then(res => {
            wx.reLaunch({
              url: `/pages/end/end`,
            })
          })

        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },
})